package com.wt.demo.future;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.*;

/**
 * @description
 * @author: wangtao
 * @date:16:54 2019/6/19
 * @email:386427665@qq.com
 */
public class ThreadCountDownLatch {

    /**
     * 设置初始计数10
     */
    private static CountDownLatch end = new CountDownLatch(10);

    private static Map<String, String> taskMap = new HashMap<>();

    static {
        taskMap.put("0", "显示屏");
        taskMap.put("1", "内存");
        taskMap.put("2", "硬盘");
        taskMap.put("3", "键盘");
        taskMap.put("4", "鼠标");
        taskMap.put("5", "触摸板");
        taskMap.put("6", "音响");
        taskMap.put("7", "cpu");
        taskMap.put("8", "风扇");
        taskMap.put("9", "显卡");
    }

    public static class CheckThread implements Runnable {
        private String taskName;

        public CheckThread(String taskName) {
            this.taskName = taskName;
        }

        @Override
        public void run() {
            try {
                //模拟耗时任务
                int i = new Random().nextInt(6) + 1;
                Thread.sleep(i * 1000);
                System.out.println("开始检查<" + taskMap.get(taskName) + "> 耗时：" + i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                //线程执行完之后，计数器减一
                end.countDown();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        System.out.println("启动计算机，开始键检查各部件是否正常...");
        ExecutorService exec = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            //开始执行其他主要线程
            exec.execute(new CheckThread(i + ""));
        }
        //end.await()会使当前线程在此处等待其他线程执行完毕，因为会卡在此处，所以一般将其放置在子线程中等待,这里使用future
        Future<Boolean> future = exec.submit(() -> {
            try {
                //在子线程当中等待，使用future
                end.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return true;
        });
        //...这里可以去做一些其他的事情
        //在需要的时候获得future的值，如果future没有执行完，还是会卡在此处
        System.out.println(future.get());
        System.out.println("检查完毕，开始启动计算机...");
        exec.shutdown();
    }
}
